import { ToastController } from 'ionic-angular/components/toast/toast-controller';
import { ViewController } from 'ionic-angular/navigation/view-controller';
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { Storage } from '@ionic/storage/dist/storage';
import { BaseUI } from '../../common/baseui';
import { LoadingController } from 'ionic-angular/components/loading/loading-controller';
import { RestProvider } from '../../providers/rest/rest';

/**
 * Generated class for the QuestionPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-question',
  templateUrl: 'question.html',
})
export class QuestionPage  extends BaseUI{

  title: string
  content: string
  errorMessage: any

  constructor(public navCtrl: NavController, 
    public viewCtrl: ViewController,
    public storage: Storage,
    public loadingCtrl: LoadingController,
    public rest: RestProvider,
    public toastCtrl: ToastController,
    public navParams: NavParams) {
      super()
  }

  dismiss() {
    this.viewCtrl.dismiss()
  }

  submitQuestion() {
    this.storage.get('userId').then(val => {
      if (val != null) {
        let loading = super.showLoading(this.loadingCtrl, '发表中...')
        this.rest.saveQuestion(val, this.title, this.content)
        .subscribe(f => {
          if (f['Status'] == 'OK') {
            loading.dismissAll()
            this.dismiss()
          } else  {
            super.showToast(this.toastCtrl, f['StatusContent'])
          }
        }, error => {
          this.errorMessage = <any> error
        })
      } else {
        super.showToast(this.toastCtrl, '请登录后发布提问...')
      }
    })
  }
}
